package com.tinem.platform.service.user.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baidu.fsg.uid.UidGenerator;
import com.tinem.platform.module.pojo.vo.error.UserException;
import com.tinem.platform.module.pojo.vo.user.RegisterReq;
import com.tinem.platform.module.starter.jpa.entity.rbac.RbacUser;
import com.tinem.platform.module.starter.jpa.repository.rbac.RbacUserRepository;
import com.tinem.platform.module.starter.sdk.MessageCode;
import com.tinem.platform.module.commons.util.PasswordUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * @author fzh
 * @version v1
 * @program: platform
 * @className UserApi
 * @description TODO
 * @site
 * @company
 * @create 2020-09-03 15:29
 */
@RestController
@RequestMapping
public class HomeApi {
    @Resource
    UidGenerator uidGenerator;
    @Resource
    RbacUserRepository rbacUserRepository;

    @PostMapping("/register.api")
    public RbacUser register(@Valid @RequestBody RegisterReq addReq) {
        if(StrUtil.isNotEmpty(addReq.getEmail())){
            RbacUser user = rbacUserRepository.findFirstByEmail(addReq.getEmail());
            if(user != null){
                throw new UserException(MessageCode.ERROR_PLATFORM_CLOUD_SERVICE_USER_EMAIL);
            }
        }
        if(StrUtil.isNotEmpty(addReq.getMobile())){
            RbacUser user = rbacUserRepository.findFirstByMobileAndCountryMobileCode(addReq.getCountryMobileCode(),addReq.getMobile());
            if(user != null){
                throw new UserException(MessageCode.ERROR_PLATFORM_CLOUD_SERVICE_USER_MOBILE);
            }
        }
        RbacUser user = new RbacUser();
        user.setId(uidGenerator.getUID());
        user.setAccount(user.getId());
        BeanUtil.copyProperties(addReq,user);
        user.setPassword(PasswordUtil.encode(user.getPassword()));

        return rbacUserRepository.saveAndFlush(user);
    }


}
